package com.dhcc.bpm.common.utils;

import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.nio.charset.Charset;

@Slf4j
public class IpAddressUtils {


	/**
	 * 本地IP地址
	 * @return
	 */
	public static void getLocalIP() {

		InetAddress addr;
		try {
			addr = InetAddress.getLocalHost();
			System.out.println("Local HostAddress:  "+addr.getHostAddress()); String
					hostname = addr.getHostName();
			System.out.println("Local host name: "+hostname);
		} catch (UnknownHostException e) {
			log.error("错误信息:{}", e);
		}

	}


	/*
	 * 获得本机公网ip
	 */
	public static String getIP() throws IOException {
		String ip = "http://pv.sohu.com/cityjson?ie=utf-8";

		String inputLine = "";
		String read = "";
		BufferedReader in = null;
		try {
			URL url = new URL(ip);
			HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
			in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
			while ((read = in.readLine()) != null) {
				inputLine += read;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			if(in != null){
				in.close();
			}
		}

		String[] split = inputLine.replace(";", "").split("=");
		JSONObject json = JSONObject.fromObject(split[1]);
		String ipstr = json.get("cip").toString();
		return ipstr;
	}

	/**
	 * 调用百度api返回ip地址的定位
	 * @return
	 * @throws IOException
	 */
	public static String getAddrName() throws IOException{
		//这里调用百度的ip定位api服务 详见 http://api.map.baidu.com/lbsapi/cloud/ip-location-api.htm
		JSONObject json = readJsonFromUrl("http://api.map.baidu.com/location/ip?ak=oBbSaFZqmC0i1CNg8rYwaSkGlmdYHbAO&ip="+getIP());
		//这里我们可以输出json看一下具体格式
		System.out.println(json.toString());

		JSONObject content=json.getJSONObject("content");              //获取json对象里的content对象
		JSONObject addr_detail=content.getJSONObject("address_detail");//从content对象里获取address_detail
		String city=addr_detail.get("city").toString();                //获取市名，可以根据具体需求更改，如果需要获取省份的名字，可以把“city”改成“province”...
		return city;
	}



	public static JSONObject readJsonFromUrl(String url) throws IOException {
		InputStream is = null;
		try {
			is = new URL(url).openStream();
			BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
			String jsonText = readAll(rd);
			JSONObject json = JSONObject.fromObject(jsonText);
			return json;
		} finally {
			//关闭输入流
			if(is !=null){
				is.close();
			}
		}
	}

	private static String readAll(Reader rd) throws IOException {
		StringBuilder sb = new StringBuilder();
		int cp;
		while ((cp = rd.read()) != -1) {
			sb.append((char) cp);
		}
		return sb.toString();
	}

}